package com.hub.videobrowsdownload

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.forest.download.State
import kotlinx.coroutines.Job
import java.io.File

abstract class BrowsVideoPrepare(val url: String, val webUrl: String) {
    val thumbPath = MutableLiveData<String?>()
    var videoWidth = MutableLiveData(0)
    var videoHeight = MutableLiveData(0)
    var videoDuration = MutableLiveData(0.0)  // M3U8 是秒，其他是 毫秒
    var videoLength = MutableLiveData(0L)
    var prepareJob: Job? = null
    var isM3U8 = false
    var title: String? = null
    val stateLiveData = MutableLiveData<Int>(0) // 1 开始预加载， 2 加载完成

    val downloadWrapper = MutableLiveData<BrowsDownLoadWrapper>()
    var downloadFilePath:String? = null
    var id:Long= 0
    var downloadSuccessTime:Long= 0
    var downloadSpeedStartSize = 0L
    var downloadSpeedStartTime = 0L
    var downloadSpeedSize = 0L
    val downloadSpeedLength = MutableLiveData<Long>(0L)
    fun getVideoId():Long {
        if (id == 0L) {
            id = System.currentTimeMillis()
        }
        return id
    }

    fun getThumbFile(context: Context): File? {
        if (thumbPath.value.isNullOrEmpty()) {
            return null
        }
        val thumbFile = File(thumbPath.value!!)
        if (thumbFile.exists()) {
            return thumbFile
        }
        val newThumbFile =
            File(thumbFile.parentFile, "download_" + thumbFile.name)
        if (newThumbFile.exists()) {
            return newThumbFile
        }
        return null
    }

    fun getPath(): String {
        return BrowsM3U8Helper.getUrlPath(url)
    }

    fun getFileName(): String {
        val path = getPath()
        val format = if (path.contains(".")) {
            path.substring(path.lastIndexOf("."))
        } else {
            ""
        }
        var pp = if (title.isNullOrEmpty() || title!!.length > 50) {
            path
        } else {
            title + format
        }
        var p = if (isM3U8) {
            if (!pp.endsWith(".ts")) {
                pp += ".ts"
            }
            pp
        } else {
            pp
        }
        if (p.contains("/")) {
            p = p.substring(p.lastIndexOf("/") + 1)
        }
        return p
    }

    fun getDownloadFile(context: Context): File {
        if (!downloadFilePath.isNullOrEmpty()) {
            return File(downloadFilePath!!)
        }

        val childDir = BrowsM3U8Helper.getDownloadFileParentDir(context, getVideoId())
        val s = System.currentTimeMillis().toString() + "_" + getFileName()
        val file = File(childDir, s)
        downloadFilePath = file.absolutePath
        return file
    }

    fun cancel() {
        try {
            try {
//                if (!thumbPath.value.isNullOrEmpty()) {
//                    File(thumbPath.value!!).delete()
//                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            prepareJob?.cancel()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun getStateMessage(value: BrowsDownLoadWrapper?):String {
        return when (value?.state) {
            is State.None -> {
                "Waiting"
            }

            is State.Waiting -> {
                "Waiting"
            }

            is State.Downloading -> {
                "Downloading"
            }

            is State.Failed -> {
                "Failed"
            }

            is State.Stopped -> {
                "Stopped"
            }

            is State.Succeed -> {// text.value = "完成"
                "Completed"
            }
            else -> {
                "Waiting"
            }
        }
    }

    fun changeThumbToDownloadFileDir(context: Context) {
        try {
            // 转移thumb
                val thumbPathValue = thumbPath.value
                if (!thumbPathValue.isNullOrEmpty()) {
                    val thumbFile = File(thumbPathValue)
                    val newThumbFile =
                        File(thumbFile.parentFile, "download_" + thumbFile.name)
                    thumbFile.renameTo(newThumbFile)
                    thumbPath.postValue(newThumbFile.absolutePath)
                }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    abstract fun prepare(
        context: Context,
        title: String?,
        videoIsWrong: ((Int, Any?) -> Unit)? = null
    ): BrowsVideoPrepare
}